package com.baidu.littlepainter.fragments.login

import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.setFragmentResultListener
import androidx.navigation.fragment.findNavController
import com.baidu.littlepainter.R
import com.baidu.littlepainter.databinding.FragmentPicLoginBinding
import com.baidu.littlepainter.databinding.FragmentPinLoginBinding
import com.baidu.littlepainter.db.User
import com.baidu.littlepainter.fragments.base.BaseFragment
import com.baidu.littlepainter.utils.PasswordType
import com.baidu.littlepainter.utils.ThreadUtils
import com.baidu.littlepainter.utils.ViewUtils
import com.baidu.littlepainter.viewmodel.MainViewModel

class PicLoginFragment: BaseFragment<FragmentPicLoginBinding>() {
    private val viewModel:MainViewModel by activityViewModels()
    private var mUser: User? = null
    override fun initBinding(): FragmentPicLoginBinding {
        return FragmentPicLoginBinding.inflate(layoutInflater)
    }

    override fun initView() {
        viewModel.setToLoginFragment()
        mBinding.tvSwitch.setOnClickListener {
            findNavController().navigate(R.id.action_picLoginFragment_to_pinLoginFragment)
        }
        //监听bottomSheetFragment传递过来的数据
        setFragmentResultListener("chooseUser"){ key, bundle ->
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                mUser = bundle.getParcelable("user", User::class.java)
            }else{
                mUser = bundle.getParcelable("user")
            }
        }

        //监听密码
        mBinding.unlockView.addPicPathFinishedListener { password ->
            if (mUser != null) {
                if (mUser!!.picPassword == password) {
                    ViewUtils.toast(requireContext(), "登录成功")
                    viewModel.login(mUser!!.name, password, PasswordType.PIC)
                    true //立刻隐藏密码图案
                } else {
                    mBinding.unlockView.showError() //显示错误
                    false //不隐藏密码图案
                }
            }else{
                true
            }
        }

        mBinding.root.setOnClickListener {
            findNavController().navigate(R.id.action_picLoginFragment_to_chooseUserFragment2)
        }
    }

    override fun onResume() {
        super.onResume()
        ThreadUtils.delayTask(500) {
            findNavController().navigate(R.id.action_picLoginFragment_to_chooseUserFragment2)
        }
    }
}